package com.mask.im.business.strategy.impl.recoverpassword;

import cn.hutool.core.lang.Validator;
import com.mask.im.business.model.entity.UserAuth;
import com.mask.im.business.common.exception.BusinessException;
import com.mask.im.business.mapper.UserAuthMapper;
import com.mask.im.business.model.vo.IdentityVerificationVO;
import com.mask.im.business.common.model.RestResponse;
import com.mask.im.business.service.RedisService;
import com.mask.im.business.strategy.RecoverPasswordStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

import static com.mask.im.business.common.constant.CommonConstant.*;
import static com.mask.im.business.common.constant.RedisConstant.EMAIL_PASSWORD_RECOVERY;

@Service("emailPasswordRecoveryImpl")
public class EmailPasswordRecoveryImpl implements RecoverPasswordStrategy {

	@Autowired
	private RedisService redisService;

	@Autowired
	private UserAuthMapper userAuthMapper;

	@Override
	public RestResponse<String> IdentityVerification(IdentityVerificationVO verificationVO) {
		modificationChecks(verificationVO.getEmail(), verificationVO.getId());
		check(verificationVO);
		redisService.del(EMAIL_PASSWORD_RECOVERY + verificationVO.getEmail());
		String token = UUID.randomUUID().toString().replaceAll("-", "");
		//将需要修改的userAuthId存入redis，方便比较和防止拦截篡改
		redisService.hSet(PASSWORD_MODIFICATION, PASSWORD_RECOVERY + token, verificationVO.getId(), 10 * 60);
		return RestResponse.ok(token);
	}

	private void modificationChecks(String email, String id) {
		UserAuth userAuth = userAuthMapper.selectById(id);
		if (Objects.isNull(userAuth)) {
			throw new BusinessException("错误请求");
		}

		if (!userAuth.getEmail().equals(email)) {
			throw new BusinessException("错误请求,请重新刷新页面");
		}

	}


	public void check(IdentityVerificationVO verificationVO) {
		if (!Validator.isEmail(verificationVO.getEmail())) {
			throw new BusinessException("邮箱格式不正确");
		}
		Object code = redisService.get(EMAIL_PASSWORD_RECOVERY + verificationVO.getEmail());
		if (Objects.isNull(code)) {
			throw new BusinessException("验证码已过期，请重新获取");
		}
		if (!verificationVO.getCode().equals(code.toString())) {
			throw new BusinessException("验证码不正确，请重新输入");
		}
	}
}
